package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"net/http/httputil"
)

var db = make(map[string]string)

// Json parse json
type Json struct {
	Value string `json:"value" binding:"required"`
}

func setupRoutes() *gin.Engine {
	// init
	r := gin.Default()
	r.Use(printLogs)

	// Ping test
	r.GET("/ping", func(ctx *gin.Context) {
		ctx.String(http.StatusOK, "pong")
	})

	// get user value
	r.GET("/user/:name", func(ctx *gin.Context) {
		user := ctx.Param("name")
		if value, ok := db[user]; ok {
			ctx.JSON(http.StatusOK, gin.H{"user": user, "value": value})
		} else {
			ctx.JSON(http.StatusOK, gin.H{"user": user, "value": "no value"})
		}
	})

	// auth
	auth := r.Group("/", gin.BasicAuth(gin.Accounts{
		"admin": "test", // user: foo, password:test@123
	}))

	// auth function
	// post Zm9vOmJhcg== is base64("foo:bar")
	auth.POST("admin", func(ctx *gin.Context) {

		user := ctx.MustGet(gin.AuthUserKey).(string)

		json := Json{}
		err := ctx.Bind(&json)
		if err != nil {
			ctx.JSON(http.StatusBadRequest, gin.H{"msg": err.Error()})
			return
		}
		db[user] = json.Value
		ctx.JSON(http.StatusOK, gin.H{"status": "ok"})
	})
	return r
}

func printLogs(ctx *gin.Context) {
	// 打印请求
	requestDump, err := httputil.DumpRequest(ctx.Request, true)
	if err != nil {
		log.Println(err)
	}
	log.Println(string(requestDump))
}

func main() {
	r := setupRoutes()
	// run and listen
	err := r.Run(":8080")
	if err != nil {
		fmt.Println(err.Error())
		return
	}

}
